package com.classload.controller;


import com.classload.domain.Order;
import com.classload.domain.Product;
import com.classload.service.OrderService;
import com.classload.service.ProductService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

//@RestController
public class OrderController {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    OrderService orderService;

    @Autowired
    ProductService productService;



    @RequestMapping("/order/message")
    public String message() {
        return "消息";
    }


    @RequestMapping("/order/product/{pid}")
    public Order createOrder(@PathVariable("pid") Integer pid) throws InterruptedException {
        // 根据 应用名称获取 服务提供者的信息  返回一个  集合  因为可能存在多实例 做负载均衡
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

//        //获取服务提供者的host和port
//        //随机的负载均衡
//        int index=new Random().nextInt(instances.size());
//        ServiceInstance serviceInstance = instances.get(index);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//
//        //查询商品
//        Product product = restTemplate.getForObject("""
//                http://%s:%s/product/%s
//                """.formatted(host, port, pid), Product.class);
//        Product product = restTemplate.getForObject("http://localhost:8081/product/" + pid, Product.class);


        //采用Rribbon 负载均衡调用 采用服务名的方式
//        Product product = restTemplate.getForObject("http://service-product/product/" + pid, Product.class);


        //采用feign调用
        Product product = productService.findByPid(pid);
        //创建订单
        Order order = new Order();
        order.setUid(1);
        order.setPid(pid);
        order.setUsername("刘丹");
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderService.createOrder(order);

        return order;
    }
}
